package com.bw.common.utils

import android.content.Context
import android.content.SharedPreferences
import com.bw.common.common.SPTypeException
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

/**
 * @author:created by hahajing
 * 时间：2024/4/24 0024
 * 企鹅号:444511958
 * 描述:利用【委托】操作SharedPreference工具类
 */
class SharedPreferenceDelegate<T>(val context: Context,val spName:String,val key:String,val defValue:T):ReadWriteProperty<Any?,T> {

    private val sp:SharedPreferences by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
        context.getSharedPreferences(spName,Context.MODE_PRIVATE)
    }

    override fun getValue(thisRef: Any?, property: KProperty<*>): T {
        val k=key?:property.name
        return when(defValue){
            is Int ->{sp.getInt(k,defValue)}
            is String ->{sp.getString(k,defValue)}
            is Boolean->{sp.getBoolean(k,defValue)}
            is Long->{sp.getLong(k,defValue)}
            is Float -> {sp.getFloat(k,defValue)}
            else->{
                throw SPTypeException("当前准备获取的sp值类型不受支持")
            }
        } as T
    }

    override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
        val k=key?:property.name
        with(sp.edit()){
            when(value){
                is Int ->{putInt(k,value)}
                is String ->{
                    putString(k,value)
                }
                is Boolean->{putBoolean(k,value)}
                is Long->{putLong(k,value)}
                is Float -> {putFloat(k,value)}
                else->{
                    throw SPTypeException("当前存储的sp值类型不受支持")
                }
            }

            apply()
        }
    }

}